package com.example.exam1.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @author Deepwind
 */
public class ResponseUtils {
    /**
     * 生成通用响应体并返回
     * @param resp HttpServletResponse
     * @param code 状态码
     * @param msg 响应信息
     * @param data 响应数据
     */
    public static void genBaseResponse(HttpServletResponse resp, int code, String msg, Object data) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("msg", msg);
        jsonObject.put("data", data);
        resp.getWriter().write(JSON.toJSONString(jsonObject));
    }

    /**
     * 封装常用的未找到响应信息
     * @param resp HttpServletResponse
     * @param msg 响应信息
     */
    public static void gen404Response(HttpServletResponse resp, String msg) throws IOException {
        genBaseResponse(resp, 404, msg, null);
    }

    /**
     * 封装常用的服务器错误响应信息
     * @param resp HttpServletResponse
     * @param msg 响应信息
     */
    public static void gen500Response(HttpServletResponse resp, String msg) throws IOException {
        genBaseResponse(resp, 500, msg, null);
    }

    /**
     * 封装常用的成功响应信息
     * @param resp HttpServletResponse
     * @param msg 响应信息
     * @param data 响应数据
     */
    public static void genSuccessResponse(HttpServletResponse resp, String msg, Object data) throws IOException {
        genBaseResponse(resp, 0, msg, data);
    }
}
